/**
 * Class LayerProperty
 */
class LayerProperty {
  constructor() {
    this.fields = [];
  }
  /**
   * 获取数据
   * @param {*} ly 
   * @returns 
   */
  getData (ly) {
    if (ly && ly._dataSource && ly._dataSource[0] && ly._dataSource[0].entities) {
      return this.getEntities(ly._dataSource[0].entities.values);

    }
    if (ly && ly._primitives && ly._primitives[0] && ly._primitives[0].root.children) {
      return this.getPrimitives(ly._primitives[0].root.children, []);
    }
  }
  /**
   * @description: 获取entity的数据
   * @param {*} arr 
   * @returns 
   * @private
   */
  getEntities(arr) {
    let resArr = [];
    for (let i = 0; i < arr.length; i++) {
      let o = arr[i].properties;
      if (this.fields.length == 0) {
        this.getFiles(o._propertyNames);
      }
      let newObj = {}; //防止卡顿
      for (let j = 0; j < o._propertyNames.length; j++) {
        let key = o._propertyNames[j];
        newObj[key] = o[key]._value;
      }
      resArr.push(newObj);
    }
    return resArr;
  }
  /**
   * @description: 获取primitives的数据
   * @param {*} arr 
   * @param {*} resArr 
   * @returns 
   * @private
   */
  getPrimitives(arr, resArr) {
    for (let i = 0; i < arr.length; i++) {
      let o = arr[i].content;
      let position = arr[i]._boundingVolume._orientedBoundingBox.center;
      if (o && o.batchTable && o.batchTable._properties) {
        let hasPro = JSON.stringify(o.batchTable._properties);
        if (hasPro == '{}') {
          break;
        } else {
          if (this.fields.length == 0) {
            let filesNames = Object.keys(o.batchTable._properties); 
            this.getFiles(filesNames);
          }
        }
        let obj = o.batchTable._properties;
        let newRes = []
        for (let index = 0; index < obj.FID.length; index++) {
          let newObj = {}
          for (let key in obj) { 
            if(obj[key] instanceof Array){  //手动处理默认第一个数据
              newObj[key] = obj[key][index]
            }else{
              newObj[key] = obj[key]
            }  
            
          } 
          if (position) {
            newObj.Position = position
          }
          newRes.push(newObj)
        }
        resArr=[...resArr,...newRes];
      } else {
        let arr1 = arr[i].children;
        this.getPrimitives(arr1, resArr);
      }
    }
    return resArr;
  }
  /**
   * @description: 对应中文名
   * @param {*} val 
   * @private
   */
  getFiles(val) {
    this.fields = [];
    for (let i = 0; i < val.length; i++) {
      let o = {
        key: val[i]+(new Date()).valueOf(),
        name: val[i],
        alias: val[i], //对应别名---待----
      };
      this.fields.push(o);
    }
  }
}

export default LayerProperty;